package com.chinamobile.websocket.websocketdispatcher.config;

import com.chinamobile.websocket.domain.dto.MessageDto;
import com.chinamobile.websocket.websocketdispatcher.common.MessageDistributorConstants;
import com.chinamobile.websocket.websocketdispatcher.distributor.MessageDistributor;
import com.chinamobile.websocket.websocketdispatcher.distributor.redis.RedisMessageDistributor;
import com.chinamobile.websocket.websocketdispatcher.distributor.redis.RedisMessageListenerInitializer;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @className: RedisMessageDistributorConfig
 * @description 基于 Redis 的消息分发器
 * @author: fanzhijun
 * @date: 2024/1/22
 **/

@ConditionalOnClass(StringRedisTemplate.class)
@ConditionalOnProperty(prefix = MessageDistributorConstants.DISTRIBUTOR_PREFIX, name = "message-distributor",
        havingValue = MessageDistributorConstants.REDIS)
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class RedisMessageDistributorConfig {

    @Bean
    @ConditionalOnMissingBean(MessageDistributor.class)
    public RedisMessageDistributor<MessageDto> messageDistributor(StringRedisTemplate stringRedisTemplate) {
        return new RedisMessageDistributor<>(stringRedisTemplate);
    }

    @Bean
    @ConditionalOnBean(RedisMessageDistributor.class)
    @ConditionalOnMissingBean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisMessageListenerInitializer redisMessageListenerInitializer(
            RedisMessageListenerContainer redisMessageListenerContainer,
            RedisMessageDistributor<MessageDto> redisWebsocketMessageListener) {
        return new RedisMessageListenerInitializer(redisMessageListenerContainer, redisWebsocketMessageListener);
    }

}
